<template>
  <div style="height: 100%">
    <!-- <callRoom ref="callRoom" /> -->
    <!-- 语音通话 -->
    <div class="box" v-if="changeType == 1">
      <div class="topIcon" @click="logout">
        <img src="../../assets/images/home/tuichu.png" />
      </div>
      <div class="testBox">
        <el-switch
          v-model="showTestBlock"
          active-color="#13ce66"
          @change="clickSwitch"
        >
        </el-switch>
      </div>
      <!-- 调试模式 -->
      <div v-show="showTestBlock" class="testContainer">
        <div>
          ws状态：
          <span v-if="wsConnected" class="online">在线</span>
          <span v-else class="disconnect">离线</span>
        </div>
        <div style="margin-top: 0.8rem">
          trtc状态：
          <span v-if="trtcConnected" class="online">在线</span>
          <span v-else class="disconnect">离线</span>
        </div>
      </div>
      <div>
        <div class="containerBox">
          <div class="callTitle">客服中心</div>
          <hr />
          <div class="centerImage">
            <div class="circleImage">
              <img src="../../assets/images/call/touxiang2.png" />
            </div>
          </div>
          <div class="statusText">通话时长：{{ h }}:{{ m }}:{{ s }}</div>
          <div v-if="oneminutes > 0 && oneminutes < 60" class="timeText">
            通话倒计时：{{ oneminutes }}s
          </div>
          <div class="timeText">{{ statusText }}</div>
        </div>
        <div class="iconBox">
          <div class="callIcon">
            <img
              style="width: 5.8rem; cursor: pointer"
              :src="callIconUrl"
              @click="callClick"
            />
          </div>
          <div class="hangupIcon">
            <img
              @click="leaveRoom"
              style="width: 5.8rem; cursor: pointer"
              src="../../assets/images/call/guaduan.png"
            />
          </div>
        </div>
      </div>
      <div class="callBox">
        <div
          id="local_stream"
          class="local-stream"
          style="width: 0.01%; height: 0.01%"
        ></div>
        <div v-for="(item, i) in remoteStream" :key="i">
          <div :class="item ? 'distant-stream' : ''" v-html="item"></div>
        </div>
      </div>
    </div>
    <!-- 视频通话 -->
    <div v-if="changeType == 2 || changeType == 3" class="allcallBox">
      <div v-show="callStatus != 'connected'" class="vedioCalling">
        <div class="videoCallingStatusText">
          通话时长：{{ h }}:{{ m }}:{{ s }}
        </div>
        <div class="topIcon" @click="logout">
          <img src="../../assets/images/home/tuichu.png" />
        </div>
        <div class="callingImageContainer">
          <div class="vediocircleImage">
            <img
              v-show="changeType == 2"
              src="../../assets/images/call/touxiang2.png"
            />
            <img
              v-show="changeType == 3"
              style="border-radius: 50%"
              src="../../assets/images/call/doctor.png"
            />
          </div>
          <div class="timeText">{{ statusText }}</div>
        </div>
      </div>
      <div v-show="callStatus == 'connected'">
        <div class="callBoxvedio">
          <div style="position: absolute; left: 46%; top: 30%">
            <img
              class="loadingIcon"
              src="../../assets/images/call/loading.gif"
            />
            <div class="loadingText">视频载入中...</div>
          </div>
          <div
            @click="changeScreen"
            id="local_stream"
            :class="myBigScreen ? 'distant-stream-vedio' : 'local-stream-vedio'"
            style=""
          ></div>
          <div
            v-for="(item, i) in remoteStream"
            :key="i"
            :class="myBigScreen ? 'distant-vedio-box' : ''"
          >
            <!-- <div
              :class="item ? 'distant-stream-vedio' : ''"
              v-html="item"
            ></div> -->
            <div
              @click="changeScreen"
              :class="
                myBigScreen ? 'local-stream-vedio' : 'distant-stream-vedio'
              "
              v-html="item"
            ></div>
          </div>
        </div>
      </div>
      <div class="vedioiconBox">
        <div class="callIcon">
          <img
            :class="
              callStatus == 'connected'
                ? 'callIconConnected'
                : 'nocallIconConnected'
            "
            :src="callIconUrl"
            @click="callClick"
          />
        </div>
        <div
          class="cameraIcon"
          @click="changeDevice('mic')"
          v-show="callStatus == 'connected'"
        >
          <img
            v-show="micOpen"
            class="micsmallImage"
            src="../../assets/images/call/micOpen.png"
          />
          <img
            v-show="!micOpen"
            class="micsmallImage"
            src="../../assets/images/call/micClose.png"
          />
        </div>
        <div
          class="cameraIcon"
          @click="changeDevice('camera')"
          v-show="callStatus == 'connected'"
        >
          <img
            v-show="cameraOpen"
            style="width: 2rem; cursor: pointer; margin-top: 1.2rem"
            src="../../assets/images/call/cameraOpen.png"
          />
          <img
            v-show="!cameraOpen"
            style="width: 2rem; cursor: pointer; margin-top: 1.2rem"
            src="../../assets/images/call/cameraClose.png"
          />
        </div>
        <div
          :class="callStatus == 'connected' ? 'hangupVedio' : 'hangupIcon'"
          @click="leaveRoom"
        >
          <img
            :class="
              callStatus == 'connected'
                ? 'callIconConnected'
                : 'nocallIconConnected'
            "
            src="../../assets/images/call/guaduan.png"
          />
        </div>
      </div>
      <div class="vedioInfo" v-show="callStatus == 'connected'">
        <div class="statusText">通话时长：{{ h }}:{{ m }}:{{ s }}</div>
        <div v-if="oneminutes > 0 && oneminutes < 60" class="timeText">
          通话倒计时：{{ oneminutes }}s
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations } from "vuex";
import { genTestUserSig } from "../../../public/debug/GenerateTestUserSig";
import TRTC from "trtc-js-sdk";
import tonghua from "../../assets/images/call/tonghua.png";
import unhujiao from "../../assets/images/call/unhujiao.png";
import mqtt from "mqtt";
import {
  MQTT_SERVICE,
  MQTT_USERNAME,
  MQTT_PASSWORD,
} from "../../utils/sysconstant";
import { mapState } from "vuex";
import { getSearchHistory } from "../../utils";
import config from "../../config";
import mp3 from "../../assets/music/voice.mp3";
//import callRoom from "@/components/call-room/index.vue";
const options = {
  connectTimeout: 40000,
  clientId: "mqttjs_" + Math.random().toString(16).substr(2, 8),
  username: MQTT_USERNAME,
  password: MQTT_PASSWORD,
  clean: true,
};
export default {
  name: "callPage",
  data() {
    return {
      businessType: 0,
      isFirstMessage: false, //是否第一次接收消息
      joinRoomSuccess: false,
      callMusic: null, //铃声
      micOpen: false, //麦克风是否开启
      cameraOpen: false, //摄像头是否开启
      myBigScreen: true,
      //changeType: 0, //选择了哪种通信方式：0：未选择展示弹窗  1：选择  2：视频
      trtcConnected: false, //trtc是否连接
      wsConnected: false, //ws是否连接
      showTestBlock: false, //是否打开调试模式
      timeout: null, //呼叫两分钟计时器
      timeover: null, //倒计时一分钟的计时器
      oneminutes: 60, //倒计时一分钟
      h: "00",
      m: "00",
      s: "00",
      callTimer: null,
      statusText: "", //当前状态
      firstEnter: true,
      remoteStream: [], //远方视频流
      localStream: null, //本地流
      callIconUrl: "../../assets/images/call/tonghua.png",
      searchInput: "",
      radio: "1",
      callUserId: "",
      searchResultList: [],
      searchHistoryUser: getSearchHistory(),
      data: ["12", "123", "1234", "12345"],
      value: "",
      TelNum: "", //当前用户的电话
      trtcClient: null, //TRTC客户端
      roomId: null, //房间号
      client: null, //ws
    };
  },
  components: {
    //callRoom,
  },
  computed: {
    ...mapState({
      profile: (state) => state.profile,//视频清晰度配置
      audioprofile: (state) => state.audioprofile,//语音配置
      changeType: (state) => state.changeType,
      currentUserId: (state) => state.currentUserId, //当前的用户id
      userInfoDetails: (state) => state.userInfoDetails,
      loginUserInfo: (state) => state.loginUserInfo,
      meetingUserIdList: (state) => state.meetingUserIdList,
      callStatus: (state) => state.callStatus,
      isAccepted: (state) => state.isAccepted,
      isInviter: (state) => state.isInviter,
    }),
    userList: function () {
      if (this.searchInput === "" && this.searchHistoryUser.length !== 0) {
        return this.searchHistoryUser;
      }
      return this.searchResultList;
    },
  },
  watch: {
    callStatus: function (newStatus, oldStatus) {
      console.log("新状态", newStatus, "旧状态", oldStatus);
      // if (newStatus === "connected") {
      //   //退出房间
      //   this.$refs.callRoom.leaveRoom();
      // }
      if (newStatus === "idle") {
        this.callIconUrl = tonghua;
        //this.$refs.callRoom.createTrtc()
      } else {
        this.callIconUrl = unhujiao;
      }
    },
  },
  created() {
    this.createTrtc();
    this.mqttMSG();
  },
  destroyed() {
    let that = this;
    //that.leaveRoom();
    console.log("销毁页面");
    //情况计时器
    clearInterval(that.callTimer);
    clearTimeout(that.timeout);
    //离开页面时，断开mqtt
    if (that.wsConnected) {
      that.client.end();
    }
  },
  mounted() {
    if (this.callStatus == "idle") {
      this.callIconUrl = tonghua;
    } else {
      this.callIconUrl = unhujiao;
    }
    console.log("mounted");
  },
  methods: {
    ...mapMutations([
      "updateCallStatus",
      //  将this.setcurrentUserId 映射为 this.$store.commit("setcurrentUserId")
    ]),
    //播放音频
    playAudio() {
      this.callMusic = null;
      this.callMusic = new Audio();
      this.callMusic.src = mp3;
      this.callMusic.loop = "loop";
      this.callMusic.play();
    },
    //停止音频
    stopAudio() {
      console.log("停止音频", this.callMusic);
      if (this.callMusic != null) {
        this.callMusic.pause();
      }
    },
    //切换麦克风或摄像头
    changeDevice(type) {
      if (type == "mic") {
        this.micOpen = !this.micOpen;
        if (this.micOpen) {
          //打开麦克风
          this.localStream.unmuteAudio();
        } else {
          //关闭麦克风
          this.localStream.muteAudio();
        }
      } else if (type == "camera") {
        this.cameraOpen = !this.cameraOpen;
        if (this.cameraOpen) {
          //打开视频
          this.localStream.unmuteVideo();
        } else {
          //关闭视频
          this.localStream.muteVideo();
        }
      }
    },
    //切换大屏小屏
    changeScreen() {
      console.log("点击切换大小");
      this.myBigScreen = !this.myBigScreen;
    },
    logout() {
      this.stopAudio();
      clearInterval(this.timeover); //十分钟倒计时的计时器
      clearInterval(this.callTimer);
      this.oneminutes = 0;
      this.callTimer = null;
      if (this.callStatus == "idle") {
        this.$router.push("/");
      }
      if (this.callStatus == "calling" && this.roomId == null) {
        let topic = "cancel_" + this.TelNum;
        let cancelMessage = {
          TelNum: this.TelNum,
          userId: this.currentUserId,
          cancel: true,
          accountName: this.userInfoDetails.account.name,
        };
        console.log("取消呼叫并发送消息", cancelMessage, this.trtcClient);
        this.client.publish(topic, JSON.stringify(cancelMessage));
        this.statusText = "取消呼叫";
      }
      let trtcClient = this.trtcClient;
      trtcClient
        .leave() //退出当前音视频通话房间，结束一次音视频通话会话。
        .then(() => {
          this.joinRoomSuccess = false; //退房
          this.trtcConnected = false;
          // 停止本地流，关闭本地流内部的音视频播放器
          this.localStream.stop();
          // 关闭本地流，释放摄像头和麦克风访问权限
          this.localStream.close();
          this.localStream = null;
          this.trtcClient = null;
          // 退房成功，可再次调用client.join重新进房开启新的通话。
          let Modeltype = 0;
          if (this.changeType == 1) {
            Modeltype = 1;
          } else {
            Modeltype = 2;
          }
          //发消息
          let mess = {
            RoomId: this.roomId,
            Type: 1, //0: join 1: Leave 2:取消
            Time: new Date().Format("yyyy-MM-dd"),
            TelNum: this.TelNum, //电话号码
            UserId: this.currentUserId,
            Modeltype: Modeltype, //1:音频 2:视频
            isAgree: false,
            accountName: this.userInfoDetails.account.name,
          };
          this.client.publish("callcenter_request", JSON.stringify(mess));
          console.log("退出房间并发送消息", mess);
          this.updateCallStatus("idle");
          this.statusText = "通话结束";
          //退出到首页
          this.$router.push("/");
        })
        .catch((error) => {
          console.error("退房失败 " + error);
          this.$router.push("/");
          // 错误不可恢复，需要刷新页面。
        });
    },
    clickSwitch() {
      //console.log("点击", this.showTestBlock);
    },
    //提示通话剩余一分钟
    endNotify() {
      //const h = this.$createElement;
      // this.$notify({
      //   title: "温馨提示",
      //   message: h(
      //     "b",
      //     { style: "color: teal" },
      //     "您已通话14分钟，一分钟后将自动挂断"
      //   ),
      // });

      if (this.changeType == 1) {
        this.$message({
          message: "您已通话14分钟，一分钟后将自动挂断",
          type: "warning",
        });
      } else if (this.changeType == 2) {
        this.$message({
          message: "您已通话9分钟，一分钟后将自动挂断",
          type: "warning",
        });
      } else if (this.changeType == 3) {
        this.$message({
          message: "您已问诊9分钟，一分钟后将自动挂断",
          type: "warning",
        });
      }
      let oneminutes = 60;
      this.oneminutes = 60;
      this.timeover = setInterval(() => {
        oneminutes--;
        this.oneminutes = oneminutes;
        if (oneminutes <= 0) {
          clearInterval(this.timeover); //清空计时器
          oneminutes = 0;
          this.leaveRoom();
        }
      }, 1000);
    },
    //点击呼叫按钮
    callClick() {
      console.log("通话状态", this.callStatus);
      if (this.callStatus == "idle") {
        //this.createTrtc();
        //this.mqttPublish();
        if (this.changeType == 3) {
          this.$router.push("consultation");
        } else {
          this.$router.push("select-type");
        }

        this.h = "00";
        this.m = "00";
        this.s = "00";
        clearInterval(this.callTimer);
        clearTimeout(this.timeout);
        this.callTimer = null;
      }
    },
    mqttMSG() {
      let that = this;
      //播放铃声
      that.playAudio();
      that.isFirstMessage = true; //是第一次接收消息
      if (that.changeType == 1) {
        that.statusText = "语音呼叫中...";
      } else if (that.changeType == 2) {
        that.statusText = "视频呼叫中...";
      } else if (that.changeType == 3) {
        that.statusText = "已通知对症医生尽快接诊，请耐心等待...";
      }
      that.TelNum = this.userInfoDetails.account.tel;
      // 创建mqtt客户端
      that.client = mqtt.connect(MQTT_SERVICE, options);
      if (!that.client.connected) {
        // mqtt连接
        that.client.on("connect", (e) => {
          console.log("**************mqtt连接成功****************", e);
          that.wsConnected = true; //ws连接成功
          let topic = "response_" + that.TelNum;
          //如果是第一次进入该页面，连接成功后直接呼叫
          //if (that.firstEnter) {
          //发送消息
          that.mqttPublish();
          //}
          //连接成功后订阅消息
          that.client.subscribe(topic, { qos: 0 }, (error) => {
            if (!error) {
              console.log("**************订阅成功**************");
            } else {
              console.log("**************订阅失败**************");
            }
          });
        });
      }
      // 接收消息处理
      that.client.on("message", (topic, message) => {
        let data = JSON.parse(message);
        console.log("收到来自", topic, "的消息", data, data.isAgree == false);
        that.stopAudio();
        if (that.isFirstMessage) {
          clearTimeout(that.timeout); //清空两分钟倒计时
          if (data.isAgree == false) {
            that.updateCallStatus("idle");
            that.$message({
              message: "暂时无人接听",
              type: "warning",
            });
            that.statusText = "暂无人接听";
            that.isFirstMessage = false;
            return;
          } else {
            that.isFirstMessage = false;
            //let roomId = data.RoomId; //Number(data.RoomId);
            if (that.businessType == 1) {
              that.roomId = Number(data.RoomId);
            } else {
              that.roomId = data.RoomId;
            }
            if (that.changeType == 3) {
              that.statusText = "医生已接诊,请等待...";
            }
            that.joinRoom(that.trtcClient, that.roomId);
          }
        }
        //that.msg = message.toString();
      });
      // 断开发起重连
      that.client.on("reconnect", (error) => {
        console.log("正在重连:", error);
      });
      //如果连接错误，打印错误
      that.client.on("error", function (err) {
        console.log("连接错误了 err=>", err);
        if (that.wsConnected) {
          that.client.end();
        }
        that.wsConnected = false;
      });
    },

    mqttPublish() {
      if (this.changeType == 1) {
        this.statusText = "语音呼叫中...";
      } else if (this.changeType == 2) {
        this.statusText = "视频呼叫中...";
      } else if (this.changeType == 3) {
        this.statusText = "已通知对症医生尽快接诊，请耐心等待...";
      }
      this.roomId = null; //初始化房间号
      let topic = "client_request";
      let Modeltype = 0;
      if (this.changeType == 1) {
        Modeltype = 1;
      } else {
        Modeltype = 2;
      }
      //订阅后发送消息
      let mess = {
        RoomId: 0,
        Type: 0, //0: join 1: Leave
        Time: new Date().Format("yyyy-MM-dd"),
        TelNum: this.TelNum, //电话号码
        UserId: this.currentUserId,
        Modeltype: Modeltype, //1:音频 2:视频
        isAgree: false,
        accountName: this.userInfoDetails.account.name,
        businessType: this.businessType, //业务类型 1：客服  2：医生
      };
      this.client.publish(topic, JSON.stringify(mess));
      this.updateCallStatus("calling");

      let that = this;
      //倒计时两分钟
      this.timeout = setTimeout(() => {
        if (that.callStatus == "calling") {
          that.stopAudio();
          that.updateCallStatus("idle");
          that.statusText = "暂无人接听";
          that.leaveRoom();
        }
      }, 1000 * 60 * 2);
      // setInterval({

      // },2*60*1000)
      console.log(
        "******************订阅成功后发送消息******************",
        mess
      );
    },
    // 计时器
    queryTime() {
      let h = 0;
      let m = 0;
      let s = 0;
      let that = this;
      that.callTimer = setInterval(function () {
        s++;
        if (s >= 60) {
          s = 0;
          that.s = s < 10 ? "0" + s : s;
          m++;
          if (m >= 60) {
            m = 0;
            that.m = m < 10 ? "0" + m : m;
            h++;
            that.h = h < 10 ? "0" + h : h;
          } else {
            that.m = m < 10 ? "0" + m : m;
          }
        } else {
          that.s = s < 10 ? "0" + s : s;
        }
        if (that.changeType == 1) {
          //语音通话，倒计时十五分钟
          if (m == "14" && s == "00") {
            //提示即将挂断
            that.endNotify();
          }
        } else if (that.changeType == 2 || that.changeType == 3) {
          //视频通话，倒计时十分钟
          if (m == "09" && s == "00") {
            console.log("aaaaaaaaaaaaaaaaaaaaaaaaaaaa");
            //提示即将挂断
            that.endNotify();
          }
        }
      }, 1000);
    },
    //创建trtc
    createTrtc() {
      if (this.changeType == 1 || this.changeType == 2) {
        this.businessType = 1;
      } else if (this.changeType == 3) {
        this.businessType = 2;
      }
      this.trtcConnected = true;
      //let TelNum = this.userInfoDetails.account.tel;
      let userId = this.currentUserId;
      if (this.businessType == 1) {
        this.trtcClient = TRTC.createClient({
          mode: "rtc",
          sdkAppId: config.SDKAppID,
          userId: userId,
          userSig: genTestUserSig(userId).userSig,
        });
      } else {
        this.trtcClient = TRTC.createClient({
          mode: "rtc",
          sdkAppId: config.SDKAppID,
          userId: userId,
          userSig: genTestUserSig(userId).userSig,
          useStringRoomId: true,
        });
      }

      // 注册远程监听
      this.subscribeStream(this.trtcClient);
      // 公共监听方法----主要是推流方摄像头关闭，音频关闭开启等；下方有说！！
      this.publicMonitor(this.trtcClient);
    },
    //加入房间
    joinRoom(trtcClient, roomId) {
      trtcClient
        .join({ roomId }) //加入一个音视频通话房间，进房代表开始一个音视频通话会话。若房间不存在，系统将自动创建一个新房间。
        .catch((error) => {
          this.stopAudio();
          console.error("进房失败 " + error);
        })
        .then(() => {
          this.stopAudio();
          console.log("进房成功");
          this.joinRoomSuccess = true;
          this.firstEnter = false;
          //创建本地流
          this.createStreams(this.userInfoDetails.account.tel);
          this.playStream(this.trtcClient);
          // setTimeout(() => {
          //   //播放远端流
          //   this.playStream(this.trtcClient);
          // }, 1000 * 6);

          //监听音量
          //this.getVolume();
          this.queryTime(); //显示通话时长
          this.updateCallStatus("connected");
          if (this.changeType == 3) {
            this.statusText = "问诊中...";
          } else {
            this.statusText = "通话中...";
          }
        });
    },
    //创建本地音视频流
    createStreams(userId) {
      let video = false;
      //判断是视频通讯还是音频
      if (this.changeType == 1) {
        video = false;
      } else if (this.changeType == 2 || this.changeType == 3) {
        video = true;
      }
      const localStream = TRTC.createStream({
        userId,
        audio: true,
        video: video,
      });
      this.micOpen = true; //打开麦克风标识
      this.cameraOpen = true; //打开摄像头标识
      this.localStream = localStream;
      let profile = this.profile;
      let audioprofile = this.audioprofile;
      // 自定义视频分辨率、帧率和码率
      localStream.setVideoProfile(profile);
      //自定义语音质量
      localStream.setAudioProfile(audioprofile);
      console.log("**************************通话时视频质量*****************************",profile)
      console.log("**************************通话时语音质量*****************************",audioprofile)
      localStream
        .initialize() //初始化本地音视频流对象
        .catch((error) => {
          console.error("初始化本地流失败 " + error);
        })
        .then(() => {
          console.log("初始化本地流成功");
          localStream.play("local_stream"); //播放该音视频流
          //自动创建 <audio> 和 <video> 标签并在指定的标签上播放音频和视频，同时该标签会被添加到页面中名为 elementId 的 div 容器。
          //创建好后才能发布
          this.publishStream(localStream, this.trtcClient);
        });
    },
    //发布本地音视频流
    publishStream(localStream, trtcClient) {
      trtcClient
        .publish(localStream) //发布本地音视频流
        .catch((error) => {
          console.error("本地流发布失败 " + error);
        })
        .then(() => {
          console.log("本地流发布成功");
        });
    },
    //获取对方音量
    getVolume() {
      this.trtcClient.on("audio-volume", (event) => {
        event.result.forEach(({ userId, audioVolume }) => {
          console.log(`userId: ${userId}, audioVolume: ${audioVolume}`);
        });
      });
      // 开启音量回调，并设置每 1000ms 触发一次事件
      this.trtcClient.enableAudioVolumeEvaluation(2000);
      // 如需关闭音量回调，传入 interval 值小于等于0即可
      //this.trtcClient.enableAudioVolumeEvaluation(-1);
    },
    //订阅远端流--加入房间之前
    subscribeStream(trtcClient) {
      trtcClient.on("stream-added", (event) => {
        const remoteStream = event.stream;
        console.log("远端流增加：" + remoteStream.getId());
        //订阅远端流
        trtcClient.subscribe(remoteStream);
      });
    },
    //播放远端流
    playStream(trtcClient) {
      trtcClient.on("stream-subscribed", (event) => {
        const remoteStream = event.stream;
        console.log("远端流订阅成功：" + remoteStream.getId());
        // 创建远端流标签，因为id是动态的，所以动态创建，用了v-html
        // const base = `<div id="${
        //   "remote_stream-" + remoteStream.getId()
        // }"  style="width:0.01%;height:0.01%"></div>`;
        let base = null;
        if (this.changeType == 1) {
          base = `<div id="${
            "remote_stream-" + remoteStream.getId()
          }"  style="width:0.01%;height:0.01%"></div>`;
        } else if (this.changeType == 2 || this.changeType == 3) {
          base = `<div id="${
            "remote_stream-" + remoteStream.getId()
          }"  style="width:100%;height:100%"></div>`;
        }
        //如果不进行初始化，会添加多个视频
        this.remoteStream = [];
        this.remoteStream.push(base);
        //做了dom操作 需要使用$nextTick(),否则找不到创建的标签无法进行播放
        this.$nextTick(() => {
          //播放
          remoteStream.play("remote_stream-" + remoteStream.getId());
        });
      });
    },
    //退出音视频
    leaveRoom() {
      this.stopAudio();
      console.log("退出时候获取的房间号", this.roomId);
      clearInterval(this.timeover); //十分钟倒计时的计时器
      clearInterval(this.callTimer);
      this.oneminutes = 0;
      this.callTimer = null;
      if (this.callStatus == "idle") {
        this.$router.push("/");
      }
      if (this.callStatus == "calling" && this.roomId == null) {
        let topic = "cancel_" + this.TelNum;
        let cancelMessage = {
          TelNum: this.TelNum,
          userId: this.currentUserId,
          cancel: true,
          accountName: this.userInfoDetails.account.name,
        };
        console.log("取消呼叫并发送消息", cancelMessage, this.trtcClient);
        this.client.publish(topic, JSON.stringify(cancelMessage));
        this.statusText = "取消呼叫";
      }
      if (!this.trtcClient) {
        return;
      }
      let trtcClient = this.trtcClient;
      trtcClient
        .leave()
        .then(() => {
          this.joinRoomSuccess = false; //退房
          this.trtcConnected = false;
          // 停止本地流，关闭本地流内部的音视频播放器
          this.localStream.stop();
          // 关闭本地流，释放摄像头和麦克风访问权限
          this.localStream.close();
          this.localStream = null;
          this.trtcClient = null;
          // 退房成功，可再次调用client.join重新进房开启新的通话。
          //发消息
          let mess = {
            RoomId: this.roomId,
            Type: 1, //0: join 1: Leave 2:取消
            Time: new Date().Format("yyyy-MM-dd"),
            TelNum: this.TelNum, //电话号码
            UserId: this.currentUserId,
            Modeltype: this.changeType == 1 ? 1 : 2, //1:音频 2:视频
            isAgree: false,
            accountName: this.userInfoDetails.account.name,
          };
          this.client.publish("callcenter_request", JSON.stringify(mess));
          console.log("退出房间并发送消息", mess);
          this.updateCallStatus("idle");
          this.statusText = "通话结束";
        })
        .catch((error) => {
          console.error("退房失败 " + error);
          if (this.firstEnter) {
            this.$router.push("/");
          } else {
            this.updateCallStatus("idle");
            this.statusText = "";
            console.log("之前已经进过房了");
          }
          // 错误不可恢复，需要刷新页面。
        });
    },
    publicMonitor(trtcClient) {
      //let that = this;
      // 新增人员
      trtcClient.on("peer-join", (evt) => {
        console.log("新增人员", evt);
      });
      // 删减人员
      trtcClient.on("peer-leave", (evt) => {
        console.log("删减人员", evt);
        //对方离开，自己挂断
        this.leaveRoom();
      });
      // 推流方关闭音频
      trtcClient.on("mute-audio", (evt) => {
        console.log("推流方关闭音频", evt);
      });
      // 推流方开启音频
      trtcClient.on("unmute-audio", (evt) => {
        console.log("推流方开启音频", evt);
      });
      //用户被踢出房间
      trtcClient.on("client-banned", (evt) => {
        console.log("用户被踢出房间事件", evt);
        this.leaveRoom();
      });
      //错误事件
      trtcClient.on("error", (evt) => {
        console.log("错误事件", evt);
      });
    },
    handleCallBtnClick: function (param) {
      if (param === this.loginUserInfo.userId) {
        this.$message("请输入正确号码");
        return;
      }
      this.callUserId = param;
      if (this.radio == "1") {
        this.CallAudio(param);
      } else {
        this.CallVideo(param);
      }
    },
    //语音电话
    CallAudio(param) {
      this.$trtcCalling.call({
        userID: param,
        type: this.TrtcCalling.CALL_TYPE.AUDIO_CALL,
        timeout: config.CallTimeout,
      });
      this.$store.commit("userJoinMeeting", this.loginUserInfo.userId);
      this.$store.commit("updateCallStatus", "calling");
      this.$store.commit("updateIsInviter", true);
      this.$router.push("/audio-call");
    },
    //视频电话
    CallVideo(param) {
      this.$trtcCalling.call({
        userID: param,
        type: this.TrtcCalling.CALL_TYPE.VIDEO_CALL,
        timeout: config.CallTimeout,
      });
      this.$store.commit("userJoinMeeting", this.loginUserInfo.userId);
      this.$store.commit("updateCallStatus", "calling");
      this.$store.commit("updateIsInviter", true);
      this.$router.push("/video-call");
    },
    handleCancelCallBtnClick: function () {
      // 对方刚接受邀请，但进房未成功
      if (this.isAccepted && this.callStatus !== "connected") {
        return;
      }
      this.callUserId = "";
      this.$trtcCalling.hangup();
      this.$store.commit("dissolveMeeting");
      this.$store.commit("updateCallStatus", "idle");
      //this.$emit("cancelCallUser");
    },
  },
};
</script>

<style scoped>
.search-user-container {
  width: 400px;
  margin: 10px auto 0;
  padding: 1px;
}
.search-section {
  display: flex;
  flex-direction: row;
}
.search-user-btn {
  margin-left: 10px;
}
.search-user-list {
  padding-top: 20px;
}
.search-user-list-title {
  margin-top: 20px;
  font-size: 18px;
  text-align: left;
}
.user-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  margin-top: 10px;
}
.video-call-section-header {
  font-size: 24px;
}
.user-item-info {
  display: flex;
  flex-direction: row;
  align-items: center;
}
.user-item-avatar-wrapper img {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
.user-item-username {
  margin-left: 20px;
}
/* @media screen and (max-width: 767px) {
  .search-user-container {
    width: 90%;
  }
} */
.box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  flex-wrap: wrap;
}
.containerBox {
  background-color: rgb(43, 46, 59);
  width: 29rem;
  height: 36rem;
  border-radius: 0.7rem;
  margin-top: -2rem;
}
.callTitle {
  background: linear-gradient(to top, #949191, #ffffff);
  -webkit-background-clip: text;
  color: transparent;
  font-weight: bold;
  padding: 0.5rem 0 0.1rem;
}
.iconBox {
  display: flex;
  justify-content: center;
  margin-top: -7.5rem;
}
.callIcon {
  margin-left: 0rem;
}
.hangupIcon {
  margin-top: 0.2rem;
  margin-left: 7rem;
}
.circleImage {
  width: 10rem;
  height: 10rem;
  background: aliceblue;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.circleImage img {
  width: 8rem;
}
.centerImage {
  width: 12rem;
  height: 12rem;
  background: #31333a;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
  margin-top: 4rem;
}
.statusText {
  color: white;
  text-align: center;
  font-size: 1.3rem;
  margin-top: 1rem;
}
.timeText {
  color: white;
  text-align: center;
  font-size: 1.3rem;
  margin-top: 0.2rem;
}
.callBox {
  position: absolute;
  top: 0rem;
  left: 0rem;
}
.testBox {
  position: absolute;
  top: 6rem;
  left: 3rem;
}
.testContainer {
  position: absolute;
  top: 8rem;
  left: 3rem;
  line-height: 1.5rem;
}
.online {
  background-color: #13ce66;
  padding: 0.3rem 0.5rem;
  border-radius: 0.3rem;
  color: white;
}
.disconnect {
  background-color: red;
  padding: 0.3rem 0.5rem;
  border-radius: 0.3rem;
  color: white;
}
.topIcon {
  position: absolute;
  top: 4rem;
  right: 0rem;
}
.topIcon img {
  width: 3.5rem;
  height: 3.5rem;
  margin-right: 2rem;
}
.dialogBox {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  flex-wrap: wrap;
  background-color: rgb(76, 76, 76);
}
.dialogContainer {
  width: 22rem;
  height: 13rem;
  background-color: white;
  border-radius: 0.7rem;
  position: relative;
}
.dialogTitle {
  padding: 0.4rem 1rem 0rem;
}
.dialogText {
  margin-top: 2rem;
  color: black;
  line-height: 1.8rem;
}
.dialogButtonBox {
  margin-top: 1rem;
}
.allcallBox {
  width: 100%;
  height: 100%;
}
.vedioCalling {
  width: 100%;
  height: 100%;
  background: linear-gradient(
    to top,
    rgb(184, 213, 217),
    rgb(127 144 175),
    rgb(100 123 166),
    rgb(60, 124, 174)
  );
  /* background-repeat: no-repeat;
  background-size: cover;
  background-image: url('../../assets/images/call/callBackground.jpeg'); */
}
.callingImageContainer {
  padding-top: 11rem;
}
.vediocircleImage {
  width: 10rem;
  height: 10rem;
  background: aliceblue;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: auto;
  margin-bottom: 2rem;
}
.vediocircleImage img {
  width: 8rem;
}
.vedioiconBox {
  display: flex;
  position: absolute;
  bottom: 4rem;
  left: 41.3rem;
}
.callBoxvedio {
  position: absolute;
  top: 0rem;
  left: 0rem;
  width: 100%;
  height: 100%;
}
.local-stream-vedio {
  width: 100%;
  height: 100%;
}
.distant-stream-vedio {
  width: 20%;
  height: 28%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
}
.vedioInfo {
  position: absolute;
  right: 1.5rem;
}
.distant-vedio-box {
  height: 100%;
}
.cameraIcon {
  width: 3.8rem;
  height: 3.8rem;
  background-color: #e6e6e6;
  border-radius: 50%;
  margin-left: 2rem;
  cursor: pointer;
}
.micsmallImage {
  width: 2rem;
  cursor: pointer;
  margin-top: 1rem;
}
.callIconConnected {
  width: 3.9rem;
  cursor: pointer;
}
.nocallIconConnected {
  width: 5.8rem;
  cursor: pointer;
}
.hangupVedio {
  margin-left: 2rem;
}
.videoCallingStatusText {
  color: white;
  text-align: right;
  font-size: 1.3rem;
  padding-top: 1.5rem;
  padding-right: 1.5rem;
}
.loadingIcon {
  width: 8rem;
  height: 8rem;
  /* line-height: 100%; */
}
.loadingText {
  font-size: 1.6rem;
}
</style>
